var ajax = require('../../utils/ajax.js');
var common = require('../../utils/common.js');
var Base = require('../base.js');
var app = getApp();

var GoodsList = function({
  page,
  scope,
  cmpt
}) {
  Base.apply(this, arguments);
  this._moduleId = 0;
  this._ty = 1; //1.商品块2.商品分类
  this._pageNum = 1;
  this.init();
}

common.extend(GoodsList, Base);

Object.assign(GoodsList.prototype, {
  /**
   * 初始化
   */
  init() {
    var _self = this;
    var cmpt = this.curCmpt;
    var dataset, block;

    this._pageNum = 1;
    this.setData({
      moreLoading: false,
      noMore: false,
      goodsList: [],
    });
    try {
      dataset = cmpt.content.dataset;
      block = dataset.block;
      _self._moduleId = block.id || block.category_id;
      _self._ty = dataset.ty || 1;
      _self._isPage = cmpt.content.isPage || '0';
      _self._showNum = cmpt.content.showNum || 10;
    } catch (e) {
      _self.setData({
        list: []
      });
      return;
    }
    _self._fetch();
  },

  /**
   * 加载更多
   */
  _loadMore: function() {
    var _self = this;
    var {
      noMore,
      moreLoading
    } = _self.getData();

    if (noMore || moreLoading) {
      return;
    }

    _self.setData({
      moreLoading: true
    });
    _self._pageNum++;
    _self._fetch();
  },

  /**
   * 获取列表数据
   */
  _fetch() {
    var _self = this;
    var {
      _ty = 1,
      _moduleId,
      _pageNum,
      _isPage,
      _showNum,
    } = this;
    var {
      goodsList
    } = _self.getData();
    var ajaxUrl = '/openapi/CHome/getDataBlockContent';
    var ajaxParams = {
      module_id: _moduleId
    };

    if (_ty == 2) {
      ajaxUrl = '/openapi/CHome/categoryPage';
      ajaxParams = {
        catId: _moduleId
      };
    }

    ajaxParams.page = _pageNum;
    if (_isPage == 0) {
      ajaxParams.page_size = _showNum || 10;
    }

    ajax.G(ajaxUrl, ajaxParams, function(res) {
      var result = res['result'];
      var list = result['dataBlockContent'] || result['goodsList'] || [];

      _self.setData({
        goodsList: goodsList.concat(list),
        moreLoading: false,
        noMore: list.length < 10
      });
    });
  }


});

GoodsList.props = {
  name: 'goodsList'
};

module.exports = GoodsList;